// pages/news/submit.js
import ImgListCell from '../../template/ImgListCell';
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    id: 0,
    lgid: 0,
    ymhid: 0,
    did: 0,
    detail: {},
    newsTitle: "",
    latitude: 0,
    longitude: 0,
    position: "",
    videoSrc: "",
    fileUrl: "",
    showType: 1,
    copyfrom: "",
    editor: "",
    relID: 0,
    sourceType: 0,
    sourceAuthor: "",
    sourceUID: 0,
    loaddinghidden: true,
    formats: {},
    keyboardHeight: 0,
    isIOS: false,
    showLoading: false,
    loadingText: '加载中...',
    columnIndex: 0,
    columnID: 0,
    columnArray: [],
    columnNameArray: [],
    imageArray: [],
    // 审核期临时关闭定位功能
    enableLocation: false,
  },
  // 从一段文本中提取“最像且最完整”的 http/https 链接
  extractBestUrl: function (text) {
    if (!text || typeof text !== 'string') return '';
    const candidates = [];
    const httpRegex = /https?:\/\//ig;
    let match;
    while ((match = httpRegex.exec(text)) !== null) {
      let i = match.index;
      let j = i;
      const isUrlChar = (ch) => /[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]/.test(ch);
      const isWhitespaceLike = (ch) => /\s/.test(ch) || /[\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF\u2060\u00AD]/.test(ch);
      // 向右扩展：允许中间穿插各种空白（空格/换行/零宽等），拼接时忽略空白
      let buf = '';
      while (j < text.length) {
        const ch = text[j];
        if (isUrlChar(ch)) {
          buf += ch;
          j++;
        } else if (isWhitespaceLike(ch)) {
          // 跳过所有空白字符
          j++;
        } else {
          break;
        }
      }
      // 基础校验（严格模式，不做任何尾部字符清理，避免改动原始 URL）
      if (buf.toLowerCase().startsWith('http')) {
        // 主机名至少包含一个点
        const hostMatch = buf.match(/^https?:\/\/([^\/\s<>"]+)/i);
        if (hostMatch && hostMatch[1].indexOf('.') !== -1) {
          candidates.push(buf);
        }
      }
      // 防止死循环：若没有前进，手动推进
      if (httpRegex.lastIndex === match.index) {
        httpRegex.lastIndex++;
      }
    }
    if (candidates.length === 0) return '';
    candidates.sort((a, b) => {
      if (b.length !== a.length) return b.length - a.length;
      const score = (s) => ((s.split('/').length - 3) + (s.includes('?') ? 1 : 0) + (s.includes('#') ? 1 : 0));
      return score(b) - score(a);
    });
    return candidates[0];
  },
  // 顶格排版：移除段落首行缩进与前导空格（&nbsp;/全角空格）
  formatAlignLeft: function () {
    var that = this;
    if (!that.editorCtx) {
      wx.showToast({ title: '编辑器未就绪', icon: 'none' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        if (!html || html === '<p><br></p>') { wx.showToast({ title: '内容为空', icon: 'none' }); return; }
        // 去除样式中的 text-indent
        html = html.replace(/text-indent\s*:\s*[^;"']+;?/gi, '');
        // 移除 <p style=""> 中可能留下的多余分号与空 style
        html = html.replace(/style="\s*;\s*"/gi, '');
        html = html.replace(/style="\s*"/gi, '');
        // 去除段落起始处的 &nbsp; 与全角空格（\u3000）
        html = html.replace(/(<p[^>]*>)(?:\s*(?:&nbsp;|\u3000))+?/gi, '$1');
        that.editorCtx.setContents({
          html: html,
          success: () => wx.showToast({ title: '已顶格', icon: 'success' }),
          fail: () => wx.showToast({ title: '排版失败', icon: 'none' })
        });
      },
      fail: () => wx.showToast({ title: '读取内容失败', icon: 'none' })
    });
  },
  // 空格排版：为每个段落添加 2em 首行缩进
  formatIndentSpace: function () {
    var that = this;
    if (!that.editorCtx) {
      wx.showToast({ title: '编辑器未就绪', icon: 'none' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        if (!html || html === '<p><br></p>') { wx.showToast({ title: '内容为空', icon: 'none' }); return; }
        // 先移除已有的 text-indent，避免叠加
        html = html.replace(/text-indent\s*:\s*[^;"']+;?/gi, '');
        // 在 <p> 上追加 text-indent:2em;
        html = html.replace(/<p(.*?)>/gi, function (m, g1) {
          if (/style\s*=\s*"[^"]*"/i.test(m)) {
            return m.replace(/style\s*=\s*"([^"]*)"/i, function (_, s) {
              var ns = (s || '').trim();
              if (ns && !/;$/ .test(ns)) ns += ';';
              return 'style="' + ns + 'text-indent:2em;"';
            });
          } else {
            return '<p style="text-indent:2em;"' + g1 + '>';
          }
        });
        that.editorCtx.setContents({
          html: html,
          success: () => wx.showToast({ title: '已缩进', icon: 'success' }),
          fail: () => wx.showToast({ title: '排版失败', icon: 'none' })
        });
      },
      fail: () => wx.showToast({ title: '读取内容失败', icon: 'none' })
    });
  },
  // 调用AI接口对当前文章标题和内容进行改写
  rewriteFromAI: function () {
    var that = this;
    // 先从编辑器获取当前内容
    if (!that.editorCtx) {
      wx.showModal({ title: '提示', content: '编辑器未就绪' });
      return;
    }
    that.editorCtx.getContents({
      success: (res) => {
        var html = res.html || '';
        var title = that.data.newsTitle || '';
        if ((!html || html === '<p><br></p>') && !title) {
          wx.showModal({ title: '提示', content: '请先填写标题或内容后再改写' });
          return;
        }

        that.showLoading('正调用千义通问AI改写中...');
        var parameter = {
          title: title,
          content: html
        };

        http.ApiPost(apiUrl.UrlAiRewrite, parameter, function (resp) {
          that.cancelLoading();
          if (!resp) {
            wx.showModal({ title: '改写失败', content: '网络异常，请稍后再试' });
            return;
          }
          // 假定后端返回 { code:1, data:{ title:'新标题', content:'新HTML' }, msg:'' }
          if (resp.code == 1 && resp.data) {
            var newTitle = resp.data.title || title;
            var newHtml = resp.data.content || html;
            that.setData({ newsTitle: newTitle });
            if (newHtml) {
              that.editorCtx.setContents({
                html: newHtml,
                success: () => { wx.showToast({ title: '改写完成', icon: 'success' }); },
                fail: () => { wx.showToast({ title: '内容设置失败', icon: 'none' }); }
              });
            } else {
              wx.showToast({ title: '改写完成', icon: 'success' });
            }
          } else {
            wx.showModal({ title: '改写失败', content: resp.msg || 'AI改写失败，请稍后再试' });
          }
        });
      },
      fail: () => {
        wx.showModal({ title: '提示', content: '无法获取编辑器内容' });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this
    var id = options.id;
    if (id) {
      that.setData({
        id: id
      })
      wx.setNavigationBarTitle({
        title: '编辑文章',
      })
      that.loadData();
    } else {
      var did = options.did;
      var lgid = options.lgid;
      var ymhid = options.ymhid;
      var cid = options.cid;
      //记者稿件
      if (did) {
        that.setData({
          did: did,
          columnID: cid
        })
        wx.setNavigationBarTitle({
          title: '',
        })
        that.loadDocData();
        //来稿文章
      } else if (lgid) {
        that.setData({
          lgid: lgid,
          columnID: cid
        })
        wx.setNavigationBarTitle({
          title: '',
        })
        that.loadLGData();
        //云媒号文章  
      } else if (ymhid) {
        that.setData({
          ymhid: ymhid,
          columnID: cid
        })
        wx.setNavigationBarTitle({
          title: '',
        })
        that.loadYMHData();
      } else {
        that.loadColumnData();
      }
    }

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    /**
            * 获取系统信息
            */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })

    // 审核期临时关闭定位：不获取定位
    if (this.data.enableLocation) {
      this.safeGetLocation();
    }
  },
  // 运行时检查定位接口可用性与授权
  checkLocationAvailability: function (needChoose, cb) {
    const canGet = !!wx.canIUse && wx.canIUse('getLocation');
    const canChoose = !!wx.canIUse && wx.canIUse('chooseLocation');
    if (!canGet || (needChoose && !canChoose)) {
      wx.showModal({
        title: '提示',
        content: '当前版本未开通定位/选点能力，请稍后重试或跳过位置填写',
        showCancel: false
      });
      typeof cb === 'function' && cb(false, { reason: 'api_unavailable' });
      return;
    }
    wx.getSetting({
      success: (res) => {
        const auth = res.authSetting && res.authSetting['scope.userLocation'];
        if (auth === false) {
          // 曾拒绝授权
          wx.showModal({
            title: '提示',
            content: '未授权位置信息，您可在设置中开启，或跳过位置填写',
            showCancel: false
          });
          cb && cb(false, { reason: 'denied' });
        } else {
          cb && cb(true);
        }
      },
      fail: () => {
        cb && cb(false, { reason: 'get_setting_fail' });
      }
    });
  },
  // 安全封装：获取定位
  safeGetLocation: function () {
    const that = this;
    this.checkLocationAvailability(false, function (ok) {
      if (!ok) return;
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          var latitude = res.latitude
          var longitude = res.longitude
          wx.setStorageSync("latitude", latitude);
          wx.setStorageSync("longitude", longitude);
          that.setData({
            latitude: latitude,
            longitude: longitude
          });
        },
        fail: function(err) {
          console.log("getLocation fail:", err);
        }
      })
    });
  },
  loadColumnData: function() {
    var that = this;

    var parameter = {};
    parameter['all'] = 0;
    //获取数据
    http.ApiGet(apiUrl.UrlColumnTree, parameter, function(res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.code == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          var columnName = [];
          var columnIndex = 0;
          var columnID = newData[0].id;

          if (that.data.columnID > 0) {
            columnID = that.data.columnID;
          }

          //编辑时加载的栏目id
          if (that.data.detail.column_id) {
            columnID = that.data.detail.column_id;
          }

          newData.map(function(item, index) {
            columnName.push(item.text);
            if (columnID == item.id) {
              columnIndex = index;
            }
          });
          that.setData({
            columnArray: newData,
            columnNameArray: columnName,
            columnID: columnID,
            columnIndex: columnIndex
          });
        }
      }
    });
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var columnArray = this.data.columnArray;
    this.setData({
      columnIndex: e.detail.value,
      columnID: columnArray[e.detail.value].id
    })
  },
  // 从栏目右侧“采集”按钮触发：读取剪贴板 URL 并直接采集
  catchFromClipboard: function() {
    var that = this;
    wx.getClipboardData({
      success(res) {
        var raw = (res && res.data) ? res.data : '';
        var url = that.extractBestUrl(raw);
        if (url) {
          that.doCatch(url);
        } else {
          wx.showModal({
            title: '提示',
            content: '剪贴板未发现以 http/https 开头的链接，请先复制链接后再试'
          });
        }
      },
      fail() {
        wx.showModal({
          title: '提示',
          content: '无法读取剪贴板，请重试或手动粘贴链接'
        });
      }
    })
  },
  chooseLocation: function() {
    var that = this;
    if (!this.data.enableLocation) {
      wx.showToast({ title: '本版本暂不提供位置功能', icon: 'none' });
      return;
    }
    var latitude = wx.getStorageSync("latitude");
    var longitude = wx.getStorageSync("longitude");
    this.checkLocationAvailability(true, function (ok) {
      if (!ok) return;
      wx.chooseLocation({
        latitude: latitude,
        longitude: longitude,
        success(res) {
          console.log(res);
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            position: res.address,
          });
        },
        fail(err) {
          console.log('chooseLocation fail:', err);
        }
      });
    });
  },
  loadData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;
    http.ApiGet(apiUrl.UrlNewsDetail, parameter, function(res) {
      if (res.code == 1) {
        that.setData({
          loaddinghidden: true,
          newsTitle: res.data.title,
          imageArray: res.data.images,
          columnID: res.data.column_id,
          detail: res.data,
          videoSrc: res.data.video_url,
          showType: res.data.show_type,
          position: res.data.position,
          copyfrom: res.data.copyfrom,
          editor: res.data.editor,
          relID: res.data.rel_id,
          sourceType: res.data.source_type,
          sourceAuthor: res.data.source_author,
          sourceUID: res.data.source_uid,
        });
        console.log("loadData");
        that.loadColumnData();
        that.onEditorReady();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  loadDocData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.did;
    http.ApiGet(apiUrl.UrlDocumentDetail, parameter, function(res) {
      if (res.code == 1) {
        that.setData({
          loaddinghidden: true,
          newsTitle: res.data.title,
          imageArray: res.data.images,
          detail: res.data,
          videoSrc: res.data.videos,
          editor: res.data.user_name,
        });
        console.log("loadDocData");
        that.loadColumnData();
        that.onEditorReady();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  loadLGData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.lgid;
    http.ApiGet(apiUrl.UrlLaigaoDetail, parameter, function(res) {

      var imageArray = [];

      if (res.thumb.length > 0) {
        imageArray.push(res.thumb);
      }

      that.setData({
        loaddinghidden: true,
        newsTitle: res.title,
        imageArray: imageArray,
        detail: res,
        videoSrc: res.video,
        editor: res.username,
        relID: res.id,
        sourceType: 2,
        sourceAuthor: res.username,
        sourceUID: res.uid,
      });
      console.log("loadLGData");
      that.loadColumnData();
      that.onEditorReady();

    });
  },
  loadYMHData: function() {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.ymhid;
    http.ApiGet(apiUrl.UrlYmhDetail, parameter, function(res) {
      if (res.code == 1) {
        that.setData({
          loaddinghidden: true,
          newsTitle: res.data.title,
          imageArray: res.data.images,
          detail: res.data,
          videoSrc: res.data.video,
          editor: res.data.ymh_name,
          relID: res.data.id,
          sourceType: 1,
          sourceAuthor: res.data.ymh_name,
          sourceUID: res.data.ymh_id,
        });
        console.log("loadYMHData");
        that.loadColumnData();
        that.onEditorReady();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (that.data.id == 0 && !that.data.detail.id) {
      console.log("检测剪切板自动采集");
      wx.getClipboardData({
        success(res) {
          var best = that.extractBestUrl(res.data || '');
          console.log(best);
          if (best) {
            wx.showModal({
              title: '检测到链接，确定采集？',
              content: best,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  that.doCatch(best);
                }
              }
            });
          }
        }
      })
    }
  },
  doCatch: function(url) {
    var that = this;

    if (url.length == 0) {
      wx.showModal({
        title: '采集网址无效',
      });
      return;
    }
    that.setData({
      loaddinghidden: false,
      loadingText: '采集中...'
    });

    var parameter = {};
    parameter['url'] = url;

    http.ApiGet(apiUrl.UrlDoCacth, parameter, function(res) {
      var result = res.result;
      if (result.errorCode == 1) {

        var imageArray = [];
        var thumb = res.data.thumb;
        var count = thumb.length;
        if (count > 3) {
          count = 3;
        }

        for (let i = 0; i < count; i++) {
          imageArray.push(thumb[i]);
        }

        that.setData({
          loaddinghidden: true,
          newsTitle: res.data.subject,
          imageArray: imageArray,
          copyfrom: res.data.laiyuan,
        });

        that.editorCtx.setContents({
          html: res.data.message,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });

        // wx.setClipboardData({
        //   data: "",
        //   success: function (res) {
        //     console.log(res);
        //   }
        // });

      } else {
        wx.showModal({
          title: result.errorMessage
        });
      }
    });
  },
  formSubmit: function(e) {

    var that = this;

    var formData = e.detail.value;


    var draft = e.detail.target.dataset.draft;
    formData["is_draft"] = draft;

    if (formData.title == "") {
      wx.showModal({
        title: '请填写标题',
      });
      return;
    }

    var columnID = that.data.columnID;
    if (columnID > 0) {
      formData["column_id"] = columnID;
    } else {
      wx.showModal({
        title: '请选择栏目',
      });
      return;
    }

    //封面
    var imageArray = that.data.imageArray;
    var imgStr = "";
    if (imageArray.length > 0) {
      imgStr = imageArray[0];
      if (imageArray.length > 1) {
        for (let j = 1; j < imageArray.length; ++j) {
          imgStr += "," + imageArray[j];
        }
      }
    }
    formData["cover"] = imgStr;

    formData["editor"] = that.data.editor;
    var showType = that.data.showType;

    var videoSrc = that.data.videoSrc;
    if (videoSrc.length > 0) {
      formData["video_url"] = videoSrc;
      showType = 3;
    }

    formData["show_type"] = showType;

    formData["position"] = that.data.position;

    var longitude = that.data.longitude;
    if (longitude > 0) {
      formData["longitude"] = longitude;
    }
    var latitude = that.data.latitude;
    if (latitude > 0) {
      formData["latitude"] = latitude;
    }

    formData["rel_id"] = that.data.relID;
    formData["source_type"] = that.data.sourceType;
    formData["source_author"] = that.data.sourceAuthor;
    formData["source_uid"] = that.data.sourceUID;

    // console.log(formData);
    // return;

    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html != "<p><br></p>") {
          var content = res.html;

          var fileUrl = that.data.fileUrl;
          if (fileUrl.length > 0) {
            content += "<p><a href='" + fileUrl + "'>附件：" + fileUrl + "</a></p>";
          }
          formData["content"] = content;
          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;

    console.log(formData);
    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlNewsAdd;
    if (that.data.id > 0) {
      url = apiUrl.UrlNewsEdit;
      formData["news_id"] = that.data.id;
    }

    http.ApiPost(url, formData, function(res) {
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      console.log("onEditorReady");
      if (detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function(res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 1)
        }
      }
    })
  },
  chooseImage: function() {
    const that = this;
    var count = that.data.imageArray.length;
    count = 3 - count;

    if (count > 0) {
      wx.chooseImage({
        count: count,
        success: function(res) {
          for (let j = 0; j < res.tempFilePaths.length; ++j) {
            that.uploadImage(res.tempFilePaths[j], 0)
          }
        }
      })
    } else {
      wx.showModal({
        title: '封面图不能超过三张！'
      });
    }

  },
  uploadImage: function(path, type) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadImg,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          // console.log(result);
          if (result.code == 1) {
            wx.hideToast();

            if (type == 1) {

              that.editorCtx.insertImage({
                src: result.data.url,
                width: '100%',
                success: function() {
                  console.log('insert image success');
                }
              })
            } else {
              that.setData({
                imageArray: that.data.imageArray.concat(result.data.url),
              })
            }
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  chooseVideo: function() {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        console.log(res)
        that.uploadVideo(res.tempFilePath);
      }
    })
  },
  delVideo: function() {
    var that = this
    wx.showModal({
      title: '确定删除？',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            videoSrc: ''
          })
        }
      }
    })
  },
  delImg: function(e) {
    var that = this;
    wx.showModal({
      title: '确定删除？',
      success: function(res) {
        if (res.confirm) {
          var imageArray = that.data.imageArray;
          var index = e.target.dataset.index
          imageArray.splice(index, 1);

          that.setData({
            imageArray: imageArray
          })
        }
      }
    })
  },
  uploadVideo: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      wx.uploadFile({
        url: apiUrl.UrlUploadVideo,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          // console.log(res);
          that.cancelLoading();
          var result = JSON.parse(res.data)
          if (result.code == 1) {
            that.setData({
              videoSrc: result.data.url,
            });
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log('err');
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  showLoading: function() {
    // 支持传入自定义文案
    let text = '加载中...';
    if (arguments && arguments.length > 0 && typeof arguments[0] === 'string') {
      text = arguments[0];
    }
    this.setData({
      showLoading: true,
      loadingText: text
    })
  },
  cancelLoading: function() {
    this.setData({
      showLoading: false
    })
  },
  fileBtnTap: function () {
    var that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        const tempFilePaths = res.tempFiles;
        console.log(tempFilePaths[0].path);
        that.uploadFile(tempFilePaths[0].path);
      }
    })
  },
  uploadFile: function (path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUpload,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function (res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          console.log(result);
          if (result.code == 1) {
            wx.hideToast();

            var fileUrl = result.data.url;

            that.setData({
              fileUrl: fileUrl
            });

          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function (err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
})